#!/bin/bash

# Docker部署测试脚本
# 用于验证Search Dashboard应用是否正确部署

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    echo -e "${2}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}

# 等待服务启动
wait_for_service() {
    local url=$1
    local service_name=$2
    local max_attempts=30
    local attempt=1
    
    print_message "等待 $service_name 服务启动..." $YELLOW
    
    while [ $attempt -le $max_attempts ]; do
        if curl -f -s $url > /dev/null 2>&1; then
            print_message "$service_name 服务已启动" $GREEN
            return 0
        fi
        
        echo -n "."
        sleep 2
        attempt=$((attempt + 1))
    done
    
    print_message "$service_name 服务启动超时" $RED
    return 1
}

# 测试API端点
test_api_endpoint() {
    local url=$1
    local description=$2
    
    print_message "测试 $description..." $BLUE
    
    response=$(curl -s -w "\n%{http_code}" $url)
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | head -n -1)
    
    if [ "$http_code" = "200" ]; then
        print_message "✅ $description 测试通过" $GREEN
        return 0
    else
        print_message "❌ $description 测试失败 (HTTP $http_code)" $RED
        echo "响应内容: $body"
        return 1
    fi
}

# 测试数据库连接
test_database() {
    print_message "测试数据库连接..." $BLUE
    
    # 通过后端API测试数据库连接
    if test_api_endpoint "http://localhost:3002/health" "数据库连接"; then
        return 0
    else
        return 1
    fi
}

# 测试前端应用
test_frontend() {
    print_message "测试前端应用..." $BLUE
    
    # 测试前端页面加载
    if curl -f -s http://localhost:3000 > /dev/null; then
        print_message "✅ 前端应用测试通过" $GREEN
        return 0
    else
        print_message "❌ 前端应用测试失败" $RED
        return 1
    fi
}



# 测试完整的用户流程
test_user_flow() {
    print_message "测试用户注册流程..." $BLUE
    
    # 生成随机测试用户
    local test_email="test_$(date +%s)@example.com"
    local test_password="test123456"
    
    # 测试用户注册
    register_response=$(curl -s -X POST \
        -H "Content-Type: application/json" \
        -d "{\"email\":\"$test_email\",\"password\":\"$test_password\"}" \
        http://localhost:3002/api/auth/register)
    
    if echo "$register_response" | grep -q "success\|token\|用户"; then
        print_message "✅ 用户注册测试通过" $GREEN
    else
        print_message "❌ 用户注册测试失败" $RED
        echo "注册响应: $register_response"
        return 1
    fi
    
    # 测试用户登录
    login_response=$(curl -s -X POST \
        -H "Content-Type: application/json" \
        -d "{\"email\":\"$test_email\",\"password\":\"$test_password\"}" \
        http://localhost:3002/api/auth/login)
    
    if echo "$login_response" | grep -q "token\|success"; then
        print_message "✅ 用户登录测试通过" $GREEN
        return 0
    else
        print_message "❌ 用户登录测试失败" $RED
        echo "登录响应: $login_response"
        return 1
    fi
}

# 显示服务状态
show_service_status() {
    print_message "显示服务状态..." $BLUE
    echo ""
    docker-compose ps
    echo ""
}

# 显示服务日志摘要
show_logs_summary() {
    print_message "显示服务日志摘要..." $BLUE
    echo ""
    echo "=== MySQL 日志 ==="
    docker-compose logs --tail=5 mysql
    echo ""
    echo "=== Backend 日志 ==="
    docker-compose logs --tail=5 backend
    echo ""
    echo "=== Frontend 日志 ==="
    docker-compose logs --tail=5 frontend
    echo ""
}

# 主测试函数
main() {
    print_message "开始部署测试..." $BLUE
    echo ""
    
    # 检查Docker服务是否运行
    if ! docker-compose ps | grep -q "Up"; then
        print_message "Docker服务未运行，请先启动服务" $RED
        print_message "运行: ./docker-build.sh start" $YELLOW
        exit 1
    fi
    
    # 显示服务状态
    show_service_status
    
    # 等待服务启动
    wait_for_service "http://localhost:3002/health" "后端API" || exit 1
    wait_for_service "http://localhost:3000" "前端应用" || exit 1
    
    echo ""
    print_message "开始功能测试..." $BLUE
    echo ""
    
    # 执行各项测试
    local test_passed=0
    local test_total=0
    
    # 测试后端健康检查
    test_total=$((test_total + 1))
    if test_api_endpoint "http://localhost:3002/health" "后端健康检查"; then
        test_passed=$((test_passed + 1))
    fi
    
    # 测试数据库连接
    test_total=$((test_total + 1))
    if test_database; then
        test_passed=$((test_passed + 1))
    fi
    
    # 测试前端应用
    test_total=$((test_total + 1))
    if test_frontend; then
        test_passed=$((test_passed + 1))
    fi
    

    
    # 测试用户流程
    test_total=$((test_total + 1))
    if test_user_flow; then
        test_passed=$((test_passed + 1))
    fi
    
    echo ""
    print_message "测试完成" $BLUE
    print_message "通过: $test_passed/$test_total" $GREEN
    
    if [ $test_passed -eq $test_total ]; then
        print_message "🎉 所有测试通过！部署成功！" $GREEN
        echo ""
        print_message "访问地址:" $BLUE
        print_message "  前端应用: http://localhost:3000" $GREEN
        print_message "  后端API: http://localhost:3002" $GREEN
        echo ""
    else
        print_message "❌ 部分测试失败，请检查日志" $RED
        show_logs_summary
        exit 1
    fi
}

# 执行主函数
main "$@"